﻿using Commission.DAL;
using Commission.Helpers;
using Commission.Models;
using Commission.Resources;
using Commission.ViewModels;
using ExportToExcel;
using Microsoft.AspNet.Identity;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Net;
using System.Web.Mvc;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace Commission.Controllers
{
    [Authorize]
    public class TransactionController : BaseController
    {
        private static int Min_Withdraw_Amount = 50;
        private static SchoolContext context = new SchoolContext();
        private TransactionRepository db = new TransactionRepository(context);
        private CustomerRepository cusDb = new CustomerRepository(context);

        public ActionResult Index(string dateFrom, string dateTo, string userName, 
            int transactionTypeId = 0)
        {
            List<TransactionHistory> list = null;
            IEnumerable<TransactionHistory> allRows = GetAllRows();

            DateTime dtFrom, dtTo;
            DateTime.TryParse(dateFrom, out dtFrom);
            DateTime.TryParse(dateTo, out dtTo);

            if (User.IsInRole(Const.AdminRoleName))
            {
                list = allRows
                    .Where(s => 
                        s.AccountType != AccountType.MinusPoint
                        && s.TransactionStatus != TransactionStatus.Cancel
                        && (dtFrom.Equals(DateTime.MinValue) || s.AccountDate.CompareTo(dtFrom) >= 0)
                        && (dtTo.Equals(DateTime.MinValue) || s.AccountDate.CompareTo(dtTo) <= 0)
                     )
                    .ToList();
            }
            else
            {
                Customer login = cusDb.GetCustomerByUserName(User.Identity.GetUserName());
                list = db.GetTransactions(login.CustomerID)
                    .Where(s =>
                        (dtFrom.Equals(DateTime.MinValue) || s.AccountDate.CompareTo(dtFrom) >= 0)
                        && (dtTo.Equals(DateTime.MinValue) || s.AccountDate.CompareTo(dtTo) <= 0)
                        && s.TransactionStatus != TransactionStatus.Cancel
                     )
                     .ToList()
                    ;
            }

            if (!string.IsNullOrEmpty(userName))
            {
                list = list
                    .Where(s => s.Customer.UserName.ToUpper().Contains(userName.ToUpper())
                        || s.Customer.Name.ToUpper().Contains(userName.ToUpper())
                        )
                    .ToList();
            }

            if (transactionTypeId == -1)
            {
                list = list
                    .Where(s => CheckUsedAmountAccountType(s))
                    .ToList();
            } else if (transactionTypeId != 0)
            {
                list = list
                    .Where(s => (int)s.AccountType == transactionTypeId)
                    .ToList();
            }

            foreach (var transaction in list)
            {
                IEnumerable<TransactionHistory> someRows = allRows
                    .Where(x => x.CustomerID == transaction.CustomerID
                        && x.AccountDate.CompareTo(transaction.AccountDate) <= 0);

                decimal cumulativeAmount = someRows
                    .Select(x => x.TotalAmount).Sum();
                transaction.CumulativeAmount = cumulativeAmount;

                decimal amount80 = someRows.Select(x => x.Amount).Sum();
                transaction.CumulativeAmount80 = amount80;

                decimal amount20 = someRows.Select(x => x.ProductAmount).Sum();
                transaction.CumulativeAmount20 = amount20;
            }

            LoadTransactionTypes();

            return View(list.OrderByDescending(c => c.UpdatedAt));
        }

        private IEnumerable<TransactionHistory> GetAllRows()
        {
            return db.Get(null, null, "Customer")
                .Where(x =>
                    x.AccountType != AccountType.MinusPoint
                    && x.TransactionStatus != TransactionStatus.Cancel
                    && x.DeletedAt == null
                );
        }

        // tổng chi tiết trả thưởng
        public ActionResult AmountDetail(string dateFrom, string dateTo, 
            string userName = "")
        {
            IList<TransactionHistorySum> details = GetAmountDetails(dateFrom, dateTo, userName);

            return View(details);
        }

        private IList<TransactionHistorySum> GetAmountDetails(string dateFrom, string dateTo,
            string userName = "")
        {
            List<TransactionGroup> list = null;
            IEnumerable<TransactionHistory> allRows = GetAllRows();

            DateTime dtFrom, dtTo;
            DateTime.TryParse(dateFrom, out dtFrom);
            DateTime.TryParse(dateTo, out dtTo);
            userName = userName.ToUpper();

            if (!dtTo.Equals(DateTime.MinValue))
            {
                dtTo = dtTo.AddDays(1).AddSeconds(-1);
            }

            bool isAdmin = User.IsInRole(Const.AdminRoleName);
            Customer login = cusDb.GetCustomerByUserName(User.Identity.GetUserName());

            list = allRows
                .Where(x =>
                    (dtFrom.Equals(DateTime.MinValue) || x.AccountDate.CompareTo(dtFrom) >= 0)
                    && (dtTo.Equals(DateTime.MinValue) || x.AccountDate.CompareTo(dtTo) <= 0)
                    && (isAdmin || x.CustomerID == login.CustomerID)
                    && (
                        string.IsNullOrEmpty(userName)
                        || x.Customer.UserName.ToUpper().Contains(userName)
                        || x.Customer.Name.ToUpper().Contains(userName))
                )
                .GroupBy(x => new { x.CustomerID, x.AccountType, x.Customer })
                .Select(x => new TransactionGroup
                {
                    CustomerId = x.Key.CustomerID,
                    Customer = x.Key.Customer,
                    AccountType = x.Key.AccountType,
                    Amount80 = x.Sum(b => b.Amount),
                    Amount20 = x.Sum(b => b.ProductAmount)
                })
                .OrderBy(x => x.CustomerId)
                .ToList()
                ;

            IList<TransactionHistorySum> details = new List<TransactionHistorySum>();

            if (list.Count > 0)
            {
                DateTime accountDate = DateTime.MinValue;
                int customerId = 0;

                TransactionHistorySum detail = null;
                decimal totalAmount = 0;

                foreach (var account in list)
                {
                    if (account.CustomerId != customerId)
                    {
                        if (customerId != 0)
                        {
                            detail.TotalAmount = totalAmount;
                        }

                        totalAmount = 0;

                        detail = new TransactionHistorySum();
                        detail.Customer = account.Customer;
                        detail.DateFrom = dateFrom;
                        detail.DateTo = dateTo;

                        details.Add(detail);

                        IEnumerable<TransactionHistory> someRows = allRows
                            .Where(x => x.CustomerID == account.CustomerId);

                        decimal cumulativeAmount = someRows
                            .Select(x => x.TotalAmount).Sum();
                        detail.CumulativeAmount = cumulativeAmount;

                        decimal amount80 = someRows
                            .Select(x => x.Amount).Sum();
                        detail.Amount80 = amount80;

                        decimal amount20 = someRows
                            .Select(x => x.ProductAmount).Sum();
                        detail.Amount20 = amount20;
                    }

                    totalAmount += account.Amount100;

                    switch (account.AccountType)
                    {
                        case AccountType.Direct:
                            detail.DirectAmount += account.Amount100;
                            break;
                        case AccountType.RollUp:
                            detail.RollupAmount += account.Amount100;
                            break;
                        case AccountType.Online:
                            detail.OnlineAmount += account.Amount100;
                            break;
                        case AccountType.Pairing:
                            detail.PairingAmount += account.Amount100;
                            break;
                        case AccountType.Matching:
                            detail.MatchingAmount += account.Amount100;
                            break;
                        case AccountType.Input:
                            detail.UsedAmount80 += account.Amount80;
                            detail.UsedAmount20 += account.Amount20;
                            break;
                        case AccountType.OnlinePayment:
                        case AccountType.SignUp:
                        case AccountType.Order:
                        case AccountType.Withdraw:
                            detail.UsedAmount80 += account.Amount100;
                            break;
                        case AccountType.Active:
                            detail.UsedAmount20 += account.Amount100;
                            break;
                    }

                    customerId = account.CustomerId;
                }

                detail.TotalAmount = totalAmount;
            }

            return details;
        }

        public ActionResult ExportAmountDetailToExcel(string dateFrom, string dateTo,
            string userName = "")
        {
            IList<TransactionHistorySum> details = GetAmountDetails(dateFrom, dateTo, userName);

            DataTable dt = DataTableUtil.ListToDataTable(details);

            string fileName = DateTime.Now.ToString("yyyyMMddHHMMss") + "_tongtienthuong.xlsx";

            CreateExcelFile.CreateExcelDocument(dt,
                fileName, HttpContext.ApplicationInstance.Response);

            return View();

        }

        public ActionResult SumIndex(string userName, string dateFrom, string dateTo)
        {
            List<TransactionHistory> list = null;
            IEnumerable<TransactionHistory> allRows = GetAllRows();

            DateTime dtFrom, dtTo;
            DateTime.TryParse(dateFrom, out dtFrom);
            DateTime.TryParse(dateTo, out dtTo);

            if (User.IsInRole(Const.AdminRoleName))
            {
                list = allRows
                    .Where(
                        x => CheckAccountType(x)
                        && (dtFrom.Equals(DateTime.MinValue) || x.AccountDate.CompareTo(dtFrom) >= 0)
                        && (dtTo.Equals(DateTime.MinValue) || x.AccountDate.CompareTo(dtTo) <= 0)
                    )
                    .OrderBy(x => x.AccountDate)
                    .ThenBy(x => x.CustomerID)
                    .ToList();
            }
            else
            {
                Customer login = cusDb.GetCustomerByUserName(User.Identity.GetUserName());
                list = db.GetTransactions(login.CustomerID)
                    .Where(
                        x => CheckAccountType(x)
                        && (dtFrom.Equals(DateTime.MinValue) || x.AccountDate.CompareTo(dtFrom) >= 0)
                        && (dtTo.Equals(DateTime.MinValue) || x.AccountDate.CompareTo(dtTo) <= 0)
                        && x.TransactionStatus != TransactionStatus.Cancel
                    )
                    .OrderBy(x => x.AccountDate)
                    .ToList();
                    ;
            }

            if (!string.IsNullOrEmpty(userName))
            {
                list = list
                    .Where(s => s.Customer.UserName.ToUpper().Contains(userName.ToUpper())
                        || s.Customer.Name.ToUpper().Contains(userName.ToUpper())
                        )
                    .ToList();
            }

            IList<TransactionHistorySum> details = new List<TransactionHistorySum>();

            if (list.Count > 0) {
                DateTime accountDate = DateTime.MinValue;
                int customerId = 0;
                TransactionHistorySum detail = null;
                // tổng hh trong 1 ngày của 1 hội viên
                decimal totalAmount = 0;

                foreach (var account in list)
                {
                    if (!account.AccountDate.Equals(accountDate)
                        || account.CustomerID != customerId)
                    {
                        if (customerId != 0)
                        {
                            detail.TotalAmount = totalAmount;
                        }

                        totalAmount = 0;

                        detail = new TransactionHistorySum();
                        detail.Customer = account.Customer;
                        detail.AccountDate = account.AccountDate;
                        details.Add(detail);

                        IEnumerable<TransactionHistory> someRows =  allRows
                            .Where(x => x.CustomerID == account.CustomerID
                                && x.AccountDate.CompareTo(account.AccountDate) <= 0);

                        decimal cumulativeAmount = someRows
                            .Select(x => x.TotalAmount).Sum();
                        detail.CumulativeAmount = cumulativeAmount;

                        decimal amount80 = someRows
                            .Select(x => x.Amount).Sum();
                        detail.Amount80 = amount80;

                        decimal amount20 = someRows
                            .Select(x => x.ProductAmount).Sum();
                        detail.Amount20 = amount20;
                    }

                    totalAmount += account.TotalAmount;

                    switch (account.AccountType)
                    {
                        case AccountType.Direct:
                            detail.DirectAmount += account.TotalAmount;
                            break;
                        case AccountType.RollUp:
                            detail.RollupAmount += account.TotalAmount;
                            break;
                        case AccountType.Online:
                            detail.OnlineAmount += account.TotalAmount;
                            break;
                        case AccountType.Pairing:
                            detail.PairingAmount += account.TotalAmount;
                            break;
                        case AccountType.Matching:
                            detail.MatchingAmount += account.TotalAmount;
                            break;
                        case AccountType.Input:
                            detail.UsedAmount80 += account.Amount;
                            detail.UsedAmount20 += account.ProductAmount;
                            break;
                        case AccountType.OnlinePayment:
                        case AccountType.SignUp:
                        case AccountType.Order:
                        case AccountType.Withdraw:
                            detail.UsedAmount80 += account.TotalAmount;
                            break;
                        case AccountType.Active:
                            detail.UsedAmount20 += account.TotalAmount;
                            break;
                    }

                    accountDate = account.AccountDate;
                    customerId = account.CustomerID;
                }

                detail.TotalAmount = totalAmount;
            }

            return View(details
                .OrderByDescending(c => c.AccountDate)
                .ThenBy(c => c.Customer.CustomerID)
                );
        }

        private bool CheckAccountType(TransactionHistory trans)
        {
            if (trans.AccountType == AccountType.MinusPoint)  {
                return false;
            }

            return true;
        }

        private bool CheckUsedAmountAccountType(TransactionHistory trans)
        {
            if (trans.AccountType == AccountType.OnlinePayment
                || trans.AccountType == AccountType.Order
                || trans.AccountType == AccountType.Withdraw
                || trans.AccountType == AccountType.Active
                || trans.AccountType == AccountType.SignUp)
            {
                return true;
            }

            return false;
        }

        public ActionResult WithdrawList(string dateFrom, string dateTo, string userName,
            string updateTransactionIds, string cancelTransactionIds, string exportTransactionIds,
            bool IsDelayed = true)
        {
            if (!string.IsNullOrEmpty(updateTransactionIds))
            {
                UpdateWithdraw(updateTransactionIds);
            }
            
            if (!string.IsNullOrEmpty(cancelTransactionIds))
            {
                CancelWithdraw(cancelTransactionIds);
            }

            List<TransactionHistory> list = null;
            DateTime dtFrom, dtTo;
            DateTime.TryParse(dateFrom, out dtFrom);
            DateTime.TryParse(dateTo, out dtTo);

            if (User.IsInRole(Const.AdminRoleName))
            {
                list = GetAllRows()
                    .Where(
                        s => s.AccountType == AccountType.Withdraw
                        && (!IsDelayed || s.TransactionStatus == TransactionStatus.Delay)
                        && (DateTime.MinValue.Equals(dtFrom) || s.AccountDate.CompareTo(dtFrom) >= 0)
                        && (DateTime.MinValue.Equals(dtTo) || s.AccountDate.CompareTo(dtTo) <= 0)
                        && (string.IsNullOrEmpty(userName) || s.ContainName(userName))
                    )
                    .ToList();
            }
            else
            {
                Customer login = cusDb.GetCustomerByUserName(User.Identity.GetUserName());

                list = db.GetTransactions(login.CustomerID)
                    .Where(
                        s => s.AccountType == AccountType.Withdraw
                        && (!IsDelayed || s.TransactionStatus == TransactionStatus.Delay)
                        && (DateTime.MinValue.Equals(dtFrom) || s.AccountDate.CompareTo(dtFrom) >= 0)
                        && (DateTime.MinValue.Equals(dtTo) || s.AccountDate.CompareTo(dtTo) <= 0)
                        && (string.IsNullOrEmpty(userName) || s.ContainName(userName))
                    )
                    .ToList()
                    ;
            }
         
            return View(list.OrderByDescending(c => c.UpdatedAt));
        }

        public void UpdateWithdraw(string transactionId)
        {
            List<string> ids = transactionId.Split(new char[] { '_' }).ToList();

            DateTime now = DateTime.Now;
            Customer login = cusDb.GetCustomerByUserName(User.Identity.GetUserName());

            foreach (var id in ids)
            {
                if (string.IsNullOrEmpty(id)) continue;

                TransactionHistory trans = db.GetTransactionById(int.Parse(id));
                if (trans != null && trans.TransactionStatus == TransactionStatus.Delay)
                {
                    trans.TransactionStatus = TransactionStatus.Finish;
                    trans.UpdatedUserId = login.CustomerID;
                    trans.UpdatedAt = now;
                    db.Update(trans);
                }
            }
            db.Save();
        }

        public void CancelWithdraw(string transactionId)
        {
            List<string> ids = transactionId.Split(new char[] { '_' }).ToList();

            DateTime now = DateTime.Now;
            Customer login = cusDb.GetCustomerByUserName(User.Identity.GetUserName());

            foreach (var id in ids)
            {
                if (string.IsNullOrEmpty(id)) continue;

                TransactionHistory trans = db.GetTransactionById(int.Parse(id));
                if (trans != null && trans.TransactionStatus == TransactionStatus.Delay)
                {
                    trans.TransactionStatus = TransactionStatus.Cancel;
                    trans.UpdatedUserId = login.CustomerID;
                    trans.UpdatedAt = now;
                    trans.Description = trans.Description + " - " + "đã hủy rút tiền";
                    db.Update(trans);
                }
            }
            db.Save();
        }

        public ActionResult ExportToExcel(string transactionIds)
        {
            List<string> ids = transactionIds.Split(new char[] { '_' }).ToList();
            List<int> idList = new List<int>();

            Func<TransactionHistory, bool> isContainTrans = (account) =>
            {
                return idList.Contains(account.ID);
            };

            foreach (var id in ids)
            {
                if (string.IsNullOrEmpty(id) || "_".Equals(id)) continue;

                idList.Add(int.Parse(id));
            }

            DataTable dt = DataTableUtil.ListToDataTable(db.Get().Where(isContainTrans));

            string fileName = DateTime.Now.ToString("yyyyMMddHHMMss") + "_ruttien.xlsx";

            CreateExcelFile.CreateExcelDocument(dt,
                fileName, HttpContext.ApplicationInstance.Response);

            return View();
        }

        private void LoadTransactionTypes()
        {
            var types = new List<SelectListItem>
            {
                new SelectListItem { 
                    Text = AccountType.Direct.ToString(), 
                    Value = ((int)AccountType.Direct).ToString() 
                },
                new SelectListItem {
                    Text = AccountType.RollUp.ToString(),
                    Value = ((int)AccountType.RollUp).ToString() 
                },
                new SelectListItem {
                    Text = AccountType.Pairing.ToString(),
                    Value = ((int)AccountType.Pairing).ToString() 
                },
                new SelectListItem {
                    Text = AccountType.Online.ToString(),
                    Value = ((int)AccountType.Online).ToString() 
                },
                new SelectListItem {
                    Text = AccountType.Matching.ToString(),
                    Value = ((int)AccountType.Matching).ToString() 
                },
                new SelectListItem {
                    Text = AccountType.Withdraw.ToString(),
                    Value = ((int)AccountType.Withdraw).ToString() 
                },
                new SelectListItem {
                    Text = AccountType.OnlinePayment.ToString(),
                    Value = ((int)AccountType.OnlinePayment).ToString() 
                },
                new SelectListItem {
                    Text = AccountType.Order.ToString(),
                    Value = ((int)AccountType.Order).ToString() 
                },
                new SelectListItem {
                    Text = AccountType.SignUp.ToString(),
                    Value = ((int)AccountType.SignUp).ToString() 
                },
                new SelectListItem {
                    Text = AccountType.Active.ToString(),
                    Value = ((int)AccountType.Active).ToString() 
                },
                new SelectListItem {
                    Text = AccountType.Input.ToString(),
                    Value = ((int)AccountType.Input).ToString() 
                },
            };

            ViewBag.TransactionTypes = types;
        }

        public IOrderedQueryable<TransactionHistory> OrderingMethod(IQueryable<TransactionHistory> query)
        {
            return query.OrderByDescending(student => student.UpdatedAt);
        }

        // GET: Account/Details/5
        public ActionResult Details(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            TransactionHistory accountHistory = db.GetByID(id);
            if (accountHistory == null)
            {
                return HttpNotFound();
            }
            return View(accountHistory);
        }

        // GET: Account/Create
        public ActionResult Withdraw()
        {
            Customer customer = cusDb.GetCustomerByUserName(User.Identity.GetUserName());
            decimal totalAmount = cusDb.GetTotalAmount80(customer.CustomerID);

            ViewBag.TotalAmount = string.Format("{0:#,0}", totalAmount);

            return View();
        }

        public ActionResult InputAmount()
        {
            InputAmountModel viewModel = new InputAmountModel
            {
            };

            return View(viewModel);
        }

        // POST: Account/Create
        // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
        // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Withdraw([Bind(Include = "Amount,Description")] TransactionHistory transaction)
        {
            if (ModelState.IsValid)
            {
                if (!CheckWithdraw(transaction))
                {
                    return View(transaction);
                }
                Customer customer = cusDb.GetCustomerByUserName(User.Identity.GetUserName());

                decimal totalAmount = cusDb.GetTotalAmount80(customer.CustomerID);
                if (Math.Abs(transaction.Amount) > totalAmount)
                {
                    ModelState.AddModelError("Amount", AppResource.ErrorWithdrawTooMuch);
                    return View();
                }

                if (transaction.Amount > 0)
                {
                    transaction.Amount *= -1;
                }

                DateTime now = DateTime.Now;
                transaction.CustomerID = customer.CustomerID;
                transaction.AccountDate = DateTime.Now.Date;
                transaction.AccountType = AccountType.Withdraw;
                transaction.TransactionStatus = TransactionStatus.Delay;
                transaction.CreatedUserId = customer.CustomerID;
                transaction.CreatedAt = now;
                transaction.UpdatedUserId = customer.CustomerID;
                transaction.UpdatedAt = now;

                db.Insert(transaction);
                try
                {
                    db.context.SaveChanges();
                }
                catch (Exception e)
                {
                    throw e;
                }
                

                return RedirectToAction("Index");
            }

            return View(transaction);
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult InputAmount([Bind(Include = "Name,UserName,DisplayAmount20,DisplayAmount80,Description")] InputAmountModel viewModel)
        {
            if (ModelState.IsValid)
            {
                /*
                if (!CheckWithdraw(transaction))
                {
                    return View(transaction);
                }
                 */
                Customer login = cusDb.GetCustomerByUserName(User.Identity.GetUserName());
                Customer customer = cusDb.GetCustomerByUserName(viewModel.UserName);

                if (!CheckInputAmount(viewModel, customer))
                {
                    return View(viewModel);
                }

                TransactionHistory trans = new TransactionHistory();
                DateTime now = DateTime.Now;
                trans.CustomerID = customer.CustomerID;
                trans.SponsoredCustomerID = login.CustomerID;
                trans.AccountDate = DateTime.Now.Date;
                trans.AccountType = AccountType.Input;
                trans.Amount = viewModel.Amount80;
                trans.ProductAmount = viewModel.Amount20;
                trans.Description = viewModel.Description;
                trans.TransactionStatus = TransactionStatus.Finish;
                trans.CreatedUserId = customer.CustomerID;
                trans.CreatedAt = now;
                trans.UpdatedUserId = customer.CustomerID;
                trans.UpdatedAt = now;

                db.Insert(trans);
                try
                {
                    db.context.SaveChanges();
                }
                catch (Exception e)
                {
                    throw e;
                }


                return RedirectToAction("Index");
            }

            return View(viewModel);
        }
        
        // GET: Account/Edit/5
        public ActionResult Edit(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            TransactionHistory accountHistory = db.GetByID(id);
            if (accountHistory == null)
            {
                return HttpNotFound();
            }
            return View(accountHistory);
        }

        // POST: Account/Edit/5
        // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
        // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Edit([Bind(Include = "ID,CustomerID,AccountType,AccountDate,Point,Amount,Description")] TransactionHistory accountHistory)
        {
            if (ModelState.IsValid)
            {
                //db.Entry(accountHistory).State = EntityState.Modified;
                //db.SaveChanges();
                return RedirectToAction("Index");
            }
            return View(accountHistory);
        }

        // GET: Account/Delete/5
        public ActionResult Delete(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            TransactionHistory accountHistory = db.GetByID(id);
            if (accountHistory == null)
            {
                return HttpNotFound();
            }
            return View(accountHistory);
        }

        // POST: Account/Delete/5
        [HttpPost, ActionName("Delete")]
        [ValidateAntiForgeryToken]
        public ActionResult DeleteConfirmed(int id)
        {
            //TransactionHistory accountHistory = db.TransactionHistories.Find(id);
            //db.TransactionHistories.Remove(accountHistory);
            //db.SaveChanges();
            return RedirectToAction("Index");
        }

        private bool CheckWithdraw(TransactionHistory transaction)
        {
            if (transaction.Amount < Min_Withdraw_Amount)
            {
                ModelState.AddModelError("Amount",
                    string.Format(AppResource.ErrorMinAmount, Min_Withdraw_Amount));
                return false;
            }

            return true;
        }

        private bool CheckInputAmount(InputAmountModel viewModel, Customer customer)
        {
            if (customer == null)
            {
                ModelState.AddModelError("UserName", AppResource.ErrUserNameIsExisted);
                return false;
            }

            if (string.IsNullOrEmpty(viewModel.DisplayAmount80)
                && string.IsNullOrEmpty(viewModel.DisplayAmount20))
            {
                ModelState.AddModelError("DisplayAmount80", AppResource.ErrorAmountIsRequired);
                return false;
            }

            try
            {
                decimal amount80 = decimal.Parse(viewModel.DisplayAmount80.Replace(",", ""));
                viewModel.Amount80 = amount80;
            }
            catch (Exception)
            {
                ModelState.AddModelError("DisplayAmount80", AppResource.ErrorAmountFormatIsNotGood);
                return false;
            }

            try
            {
                decimal amount20 = decimal.Parse(viewModel.DisplayAmount20.Replace(",", ""));
                viewModel.Amount20 = amount20;
            }
            catch (Exception)
            {
                ModelState.AddModelError("DisplayAmount20", AppResource.ErrorAmountFormatIsNotGood);
                return false;
            }

            return true;
        }

        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                // TODO
                //db.context.Dispose();
            }
            base.Dispose(disposing);
        }
    }
}
